package com.ljq.cksp.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author:ljq
 * @Date:2020/4/5
 */
@Component
public class PythonUtil {
    static private String PYTHON_URL;

    @Value("${cksp.pythonUrl}")
    public void setPythonUrl(String url){
        PythonUtil.PYTHON_URL = url;
    }
    public static void s(){
        System.out.println(PYTHON_URL);
    }

    public static String sendRequest(String fact, String mode){
        StringBuilder result = new StringBuilder();
        try{
            URL url = new URL(PYTHON_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write("fact="+fact+"&mode="+mode);
            pw.flush();
            pw.close();

            connection.connect();
            int responseCode = connection.getResponseCode();
            if(responseCode == HttpURLConnection.HTTP_OK){
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    result.append(line);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
}
